package com.yyw.h5gameqianguoshu;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;

import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;


import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;
import com.yayawan.callback.YYWAnimCallBack;
import com.yayawan.callback.YYWExitCallback;
import com.yayawan.main.Kgame;
import com.yayawan.utils.DeviceUtil;
import com.yayawan.utils.Yayalog;
import com.yyw.game.R;



import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import com.tencent.smtt.sdk.*;



public class GameActivity extends Activity {
	/**
	 * 作为一个浏览器的示例展示出来，采用android+web的模式
	 */

	
	private static  String mHomeUrl = "https://api.kingoo.com.cn/h5/m_dpdzzandroidmubao/?apilogin=android&hideball=1";//全民主公
	private static final String TAG = "SdkDemo";
	private static final int MAX_LENGTH = 14;
	private boolean mNeedTestPage = false;
	private final int disable = 120;
	private final int enable = 255;
	private ProgressBar mPageLoadingProgressBar = null;
	private URL mIntentUrl;
	private Timer mTimer;
    public Activity mActivity;
	
    
    //uiHandler在主线程中创建，所以自动绑定主线程
    private static Handler uiHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1314:
                	Yayalog.loger("进来了");
                    if (!GameApi.isloginsuc) {
                    	Yayalog.loger("进来了,没有登陆成功");
                    	uiHandler.sendEmptyMessageDelayed(1314, 2000);
					}else {
						Yayalog.loger("进来了,登陆成功");
                        rootbackground.setVisibility(View.GONE);
						rl_webview.setVisibility(View.VISIBLE);
					}
                	
                    break;
                case 1315:
                   
                   
                    break;
            }
        }
    };

    
    
	@SuppressLint("SourceLockedOrientationActivity")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mActivity=this;

		//保持屏幕常亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //防止输入法遮挡文字。
      //  getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

		//去掉titile bar
		//requestWindowFeature(Window.FEATURE_NO_TITLE);
		//设置全屏
		//getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

		// 隐藏顶部的状态栏
		//getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		 hideBottomUIMenu();
        //设置布局
		setContentView(R.layout.activity_x5view);



		Kgame.getInstance().initSdk(this);

		
		//sdk 闪屏
		Kgame.getInstance().anim(this, new YYWAnimCallBack() {

			@Override
			public void onAnimSuccess(String arg0, Object arg1) {
				// TODO Auto-generated method stub

				
			}

			@Override
			public void onAnimFailed(String arg0, Object arg1) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimCancel(String arg0, Object arg1) {
				// TODO Auto-generated method stub

			}
		});

		Kgame.getInstance().onCreate(this);
		mHomeUrl=DeviceUtil.getGameInfo(mActivity, "GameUrl");
		//sdk oncreate


		Yayalog.loger("当前h链接"+mHomeUrl);
		


		//rl_webview.setVisibility(View.GONE);
		init();
	}

	public  void showToast(String msg){
		Toast.makeText(GameActivity.this,msg,Toast.LENGTH_LONG).show();
	}
	public  void  afterPermission(){

	}


	
	private void goTogame(){
		
		
	}

	public void hasPerMissson(){

	}


	static RelativeLayout rl_webview;
	private static X5WebView mWebView;
	static LinearLayout rootbackground;
	@SuppressLint("NewApi")
	private void init() {

		
		rl_webview = (RelativeLayout) findViewById(R.id.rl_webview);
		
		
		
		mWebView = (X5WebView) findViewById(R.id.webView1);

        rootbackground=(LinearLayout)findViewById(R.id.rootbackground);
//		if (DeviceUtil.isLandscape(this)){
         //   rootbackground.setBackgroundResource(R.drawable.logolan);

//		}else {
           rootbackground.setBackgroundResource(R.drawable.logopor);
//		}

        rootbackground.setClickable(true);
        rootbackground.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Yayalog.loger("rootviewonclick");
				GameApi.isloginisshow=false;
				initUrl();
			}
		});
		//rootview.setVisibility(View.GONE);
		gameApi = new GameApi(this, mWebView);
		mWebView.addJavascriptInterface(new GameApi(this, mWebView), "GameApi");
		//
		mWebView.setWebViewClient(new WebViewClient() {

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				System.out.println("开始的登陆："+url);
				
				//rl_webview.setVisibility(View.VISIBLE);
				
				return super.shouldOverrideUrlLoading(view, url);

			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				

			}

		});

		mWebView.setWebChromeClient(new WebChromeClient() {

			/**
			 * 全屏播放配置
			 */
			@Override
			public void onShowCustomView(View view,
					IX5WebChromeClient.CustomViewCallback customViewCallback) {
			
			}

			@Override
			public void onHideCustomView() {
			
			}

		});

		WebSettings webSetting = mWebView.getSettings();
		webSetting.setAllowFileAccess(true);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSetting.setMixedContentMode(1);
        }

	//	webSetting.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
		webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
		webSetting.setSupportZoom(true);
		webSetting.setBuiltInZoomControls(true);
		webSetting.setUseWideViewPort(true);
		webSetting.setSupportMultipleWindows(false);
		webSetting.setJavaScriptEnabled(true);
		//关闭android p的对话框
		//closeAndroidPDialog();
	
		initUrl();

	}

	public String msgerr="";
	//初始化url
	public void initUrl(){
		
		System.out.println("加載的url："+mHomeUrl);
		
		GameApi.isloginisshow=false;

		mWebView.loadUrl(mHomeUrl);
		//mWebView.loadUrl("http://www.baidu.com");
		//两秒后检查是否加载登陆成功
		uiHandler.sendEmptyMessageDelayed(1314, 1000);
		
	}
	
	
	public void clearWebViewCache() {
		// 清除cookie即可彻底清除缓存
		CookieSyncManager cookieSyncManager = CookieSyncManager
				.createInstance(getApplicationContext());
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.setAcceptCookie(true);
		cookieManager.removeSessionCookie();
		cookieManager.removeAllCookie();

	}

	boolean[] m_selected = new boolean[] { true, true, true, true, false,
			false, true };

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Kgame.getInstance().exit(this, new YYWExitCallback() {
				@Override
				public void onExit() {
					
					finish();
				}
			});
			return true;
		}else {
			return super.onKeyDown(keyCode, event);
		}
		
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		Kgame.getInstance().onActivityResult(this, requestCode, resultCode,
				data);

	}

	@Override
	protected void onNewIntent(Intent intent) {
		Kgame.getInstance().onNewIntent(intent);
		if (intent == null || mWebView == null || intent.getData() == null)
			return;
		mWebView.loadUrl(intent.getData().toString());
	}

	@Override
	protected void onDestroy() {

		if (mWebView != null)
			mWebView.destroy();
		super.onDestroy();
		Kgame.getInstance().onDestroy(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mWebView!=null) {
			mWebView.onResume();
		}
		
		Kgame.getInstance().onResume(this);
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		Kgame.getInstance().onRestart(this);

	}

	@Override
	protected void onPause() {
		super.onPause();
		if (mWebView!=null) {
			mWebView.onPause();
		}
		
		Kgame.getInstance().onPause(this);
	}

	@Override
	protected void onStop() {
		super.onStop();
		
		Kgame.getInstance().onStop(this);
	}


    /**
     * 隐藏虚拟按键，并且全屏
     */


    protected void hideBottomUIMenu(){
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if ( Build.VERSION.SDK_INT>= 19 && Build.VERSION.SDK_INT < 28) {
           // Toast.makeText(this,"api dayu 19",Toast.LENGTH_SHORT).show();
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                    | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE;
            decorView.setSystemUiVisibility(uiOptions);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        }else if (Build.VERSION.SDK_INT >= 28) {
            //Toast.makeText(this,"api dayu 21",Toast.LENGTH_SHORT).show();
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                    | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE;
            decorView.setSystemUiVisibility(uiOptions);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;

        }
    }
	
	private void closeAndroidPDialog(){
        try {
            Class aClass = Class.forName("android.content.pm.PackageParser$Package");
            Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class);
            declaredConstructor.setAccessible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            Class cls = Class.forName("android.app.ActivityThread");
            Method declaredMethod = cls.getDeclaredMethod("currentActivityThread");
            declaredMethod.setAccessible(true);
            Object activityThread = declaredMethod.invoke(null);
            Field mHiddenApiWarningShown = cls.getDeclaredField("mHiddenApiWarningShown");
            mHiddenApiWarningShown.setAccessible(true);
            mHiddenApiWarningShown.setBoolean(activityThread, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



	public static final int MSG_OPEN_TEST_URL = 0;
	public static final int MSG_INIT_UI = 1;
	private final int mUrlStartNum = 0;
	private int mCurrentUrl = mUrlStartNum;
	private GameApi gameApi;



    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        // TODO Auto-generated method stub
        super.onWindowFocusChanged(hasFocus);
        hideBottomUIMenu();
    }
	
	ProgressDialog progressDialog = null;

	private void progress(Activity paramActivity) {
		progressDialog = new ProgressDialog(paramActivity);
		// 设置进度条风格，风格为圆形，旋转的
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		// 设置ProgressDialog 标题
		// progressDialog.setTitle("提示");
		// 设置ProgressDialog 提示信息
		progressDialog.setMessage("正在加载。。。");
		// 设置ProgressDialog 标题图标
		// progressDialog.setIcon(R.drawable.a);
		// 设置ProgressDialog 的进度条是否不明确
		progressDialog.setIndeterminate(true);
		// 设置ProgressDialog 是否可以按退回按键取消
		progressDialog.setCancelable(false);
		// 设置ProgressDialog 的一个Button
		// progressDialog.setButton("确定", new SureButtonListener());
		// 让ProgressDialog显示
		try {
			progressDialog.show();
		} catch (Exception e) {

		}
	}

	
	
	private void disprogress() {
		if (progressDialog != null) {
			if (progressDialog.isShowing())
				progressDialog.dismiss();
		}
	}
	
}
